// 存档系统
class SaveSystem {
    constructor() {
        this.saveKey = 'timeecho_save';
        this.settingsKey = 'timeecho_settings';
        this.achievementsKey = 'timeecho_achievements';
        this.backupKey = 'timeecho_backup';
        this.quickSaveKey = 'timeecho_quicksave';
        this.maxBackups = 3;
        this.maxQuickSaves = 3;
        
        this.init();
    }

    init() {
        // 检查本地存储可用性
        this.checkStorageAvailability();
        
        // 创建备份系统
        this.setupBackupSystem();
        
        // 绑定页面卸载事件进行自动保存
        this.setupAutoSave();
        
        // 设置快速存档系统
        this.setupQuickSaveSystem();
        
        console.log('✓ 存档系统已初始化');
    }

    checkStorageAvailability() {
        try {
            const testKey = 'timeecho_test';
            localStorage.setItem(testKey, 'test');
            localStorage.removeItem(testKey);
            this.storageAvailable = true;
        } catch (error) {
            this.storageAvailable = false;
            console.warn('本地存储不可用，将使用内存存储');
            this.memoryStorage = {};
        }
    }

    setupBackupSystem() {
        // 检查是否需要创建备份
        const saveData = this.loadGameData();
        if (saveData && saveData.timestamp) {
            this.createBackup(saveData);
        }
    }

    setupAutoSave() {
        // 页面卸载时自动保存
        window.addEventListener('beforeunload', () => {
            if (window.gameEngine && window.gameEngine.hasUnsavedProgress()) {
                const autoSaveEnabled = this.getSetting('autoSave', true);
                if (autoSaveEnabled) {
                    this.saveGame(window.gameEngine.getGameState(), true);
                }
            }
        });

        // 定期自动备份（每5分钟）
        setInterval(() => {
            const autoSaveEnabled = this.getSetting('autoSave', true);
            if (autoSaveEnabled && window.gameEngine && window.gameEngine.hasUnsavedProgress()) {
                this.createQuickBackup();
            }
        }, 5 * 60 * 1000);
    }

    // 游戏数据保存和加载
    saveGame(gameState, isAutoSave = false) {
        try {
            const saveData = {
                version: '1.0.0',
                gameState: gameState,
                timestamp: Date.now(),
                isAutoSave: isAutoSave,
                language: window.i18n ? window.i18n.getCurrentLanguage() : 'zh'
            };

            this.setItem(this.saveKey, JSON.stringify(saveData));
            
            // 如果不是自动保存，创建备份
            if (!isAutoSave) {
                this.createBackup(saveData);
            }

            return true;
        } catch (error) {
            console.error('保存游戏失败:', error);
            return false;
        }
    }

    loadGame() {
        try {
            const saveData = this.loadGameData();
            if (!saveData) {
                return null;
            }

            // 检查版本兼容性
            if (!this.isVersionCompatible(saveData.version)) {
                console.warn('存档版本不兼容');
                return null;
            }

            return saveData.gameState;
        } catch (error) {
            console.error('加载游戏失败:', error);
            return null;
        }
    }

    loadGameData() {
        const savedData = this.getItem(this.saveKey);
        if (!savedData) {
            return null;
        }

        try {
            return JSON.parse(savedData);
        } catch (error) {
            console.error('解析存档数据失败:', error);
            return null;
        }
    }

    hasSaveData() {
        return this.getItem(this.saveKey) !== null;
    }

    deleteSave() {
        try {
            this.removeItem(this.saveKey);
            return true;
        } catch (error) {
            console.error('删除存档失败:', error);
            return false;
        }
    }

    // 设置保存和加载
    saveSetting(key, value) {
        try {
            const settings = this.loadSettings();
            settings[key] = value;
            this.setItem(this.settingsKey, JSON.stringify(settings));
            return true;
        } catch (error) {
            console.error('保存设置失败:', error);
            return false;
        }
    }

    getSetting(key, defaultValue = null) {
        try {
            const settings = this.loadSettings();
            return settings.hasOwnProperty(key) ? settings[key] : defaultValue;
        } catch (error) {
            console.error('加载设置失败:', error);
            return defaultValue;
        }
    }

    loadSettings() {
        const settingsData = this.getItem(this.settingsKey);
        if (!settingsData) {
            return {};
        }

        try {
            return JSON.parse(settingsData);
        } catch (error) {
            console.error('解析设置数据失败:', error);
            return {};
        }
    }

    saveAllSettings(settings) {
        try {
            this.setItem(this.settingsKey, JSON.stringify(settings));
            return true;
        } catch (error) {
            console.error('保存所有设置失败:', error);
            return false;
        }
    }

    // 成就数据保存和加载
    saveAchievements(achievements) {
        try {
            const achievementData = {
                achievements: Array.from(achievements),
                timestamp: Date.now()
            };
            this.setItem(this.achievementsKey, JSON.stringify(achievementData));
            return true;
        } catch (error) {
            console.error('保存成就失败:', error);
            return false;
        }
    }

    loadAchievements() {
        const achievementData = this.getItem(this.achievementsKey);
        if (!achievementData) {
            return new Set();
        }

        try {
            const data = JSON.parse(achievementData);
            return new Set(data.achievements || []);
        } catch (error) {
            console.error('加载成就失败:', error);
            return new Set();
        }
    }

    // 备份系统
    createBackup(saveData) {
        try {
            const backups = this.loadBackups();
            
            // 添加新备份
            backups.unshift({
                ...saveData,
                backupId: this.generateBackupId(),
                originalTimestamp: saveData.timestamp
            });

            // 限制备份数量
            if (backups.length > this.maxBackups) {
                backups.splice(this.maxBackups);
            }

            this.setItem(this.backupKey, JSON.stringify(backups));
            return true;
        } catch (error) {
            console.error('创建备份失败:', error);
            return false;
        }
    }

    createQuickBackup() {
        if (window.gameEngine) {
            const gameState = window.gameEngine.getGameState();
            const quickBackupData = {
                version: '1.0.0',
                gameState: gameState,
                timestamp: Date.now(),
                isQuickBackup: true,
                language: window.i18n ? window.i18n.getCurrentLanguage() : 'zh'
            };
            
            this.setItem('timeecho_quickbackup', JSON.stringify(quickBackupData));
        }
    }

    loadBackups() {
        const backupData = this.getItem(this.backupKey);
        if (!backupData) {
            return [];
        }

        try {
            return JSON.parse(backupData);
        } catch (error) {
            console.error('加载备份失败:', error);
            return [];
        }
    }

    restoreFromBackup(backupId) {
        try {
            const backups = this.loadBackups();
            const backup = backups.find(b => b.backupId === backupId);
            
            if (!backup) {
                console.error('备份不存在:', backupId);
                return false;
            }

            // 先备份当前存档
            const currentSave = this.loadGameData();
            if (currentSave) {
                this.createBackup(currentSave);
            }

            // 恢复备份
            const restoreData = {
                version: backup.version,
                gameState: backup.gameState,
                timestamp: Date.now(),
                restoredFrom: backup.backupId,
                language: backup.language
            };

            this.setItem(this.saveKey, JSON.stringify(restoreData));
            return true;
        } catch (error) {
            console.error('恢复备份失败:', error);
            return false;
        }
    }

    // 数据导出和导入
    exportSaveData() {
        try {
            const exportData = {
                version: '1.0.0',
                exportTimestamp: Date.now(),
                gameData: this.getItem(this.saveKey),
                settingsData: this.getItem(this.settingsKey),
                achievementsData: this.getItem(this.achievementsKey),
                backupsData: this.getItem(this.backupKey)
            };

            const jsonString = JSON.stringify(exportData, null, 2);
            const blob = new Blob([jsonString], { type: 'application/json' });
            const url = URL.createObjectURL(blob);

            const link = document.createElement('a');
            link.href = url;
            link.download = `timeecho_save_${new Date().toISOString().slice(0, 10)}.json`;
            link.click();

            URL.revokeObjectURL(url);
            return true;
        } catch (error) {
            console.error('导出存档失败:', error);
            return false;
        }
    }

    importSaveData(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            
            reader.onload = (e) => {
                try {
                    const importData = JSON.parse(e.target.result);
                    
                    // 验证导入数据
                    if (!this.validateImportData(importData)) {
                        reject(new Error('无效的导入数据'));
                        return;
                    }

                    // 备份当前数据
                    this.createFullBackup();

                    // 导入数据
                    if (importData.gameData) {
                        this.setItem(this.saveKey, importData.gameData);
                    }
                    if (importData.settingsData) {
                        this.setItem(this.settingsKey, importData.settingsData);
                    }
                    if (importData.achievementsData) {
                        this.setItem(this.achievementsKey, importData.achievementsData);
                    }
                    if (importData.backupsData) {
                        this.setItem(this.backupKey, importData.backupsData);
                    }

                    resolve(true);
                } catch (error) {
                    reject(error);
                }
            };

            reader.onerror = () => {
                reject(new Error('文件读取失败'));
            };

            reader.readAsText(file);
        });
    }

    // 数据清理和管理
    clearAllData() {
        try {
            this.removeItem(this.saveKey);
            this.removeItem(this.settingsKey);
            this.removeItem(this.achievementsKey);
            this.removeItem(this.backupKey);
            this.removeItem('timeecho_quickbackup');
            return true;
        } catch (error) {
            console.error('清理数据失败:', error);
            return false;
        }
    }

    getStorageUsage() {
        if (!this.storageAvailable) {
            return { used: 0, available: 0, percentage: 0 };
        }

        try {
            let totalSize = 0;
            for (let key in localStorage) {
                if (key.startsWith('timeecho_')) {
                    totalSize += localStorage[key].length;
                }
            }

            // 估算可用空间（大多数浏览器限制为5-10MB）
            const estimatedLimit = 5 * 1024 * 1024; // 5MB
            const percentage = (totalSize / estimatedLimit) * 100;

            return {
                used: totalSize,
                available: estimatedLimit - totalSize,
                percentage: Math.min(percentage, 100)
            };
        } catch (error) {
            console.error('获取存储使用情况失败:', error);
            return { used: 0, available: 0, percentage: 0 };
        }
    }

    // 工具方法
    generateBackupId() {
        return `backup_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }

    isVersionCompatible(version) {
        // 简单的版本兼容性检查
        const currentVersion = '1.0.0';
        const currentParts = currentVersion.split('.').map(Number);
        const saveParts = version.split('.').map(Number);

        // 主版本号必须相同
        return currentParts[0] === saveParts[0];
    }

    validateImportData(data) {
        return data && 
               typeof data === 'object' && 
               data.version && 
               data.exportTimestamp;
    }

    createFullBackup() {
        const fullBackup = {
            timestamp: Date.now(),
            gameData: this.getItem(this.saveKey),
            settingsData: this.getItem(this.settingsKey),
            achievementsData: this.getItem(this.achievementsKey)
        };

        this.setItem('timeecho_fullbackup', JSON.stringify(fullBackup));
    }

    // 抽象存储方法
    setItem(key, value) {
        if (this.storageAvailable) {
            localStorage.setItem(key, value);
        } else {
            this.memoryStorage[key] = value;
        }
    }

    getItem(key) {
        if (this.storageAvailable) {
            return localStorage.getItem(key);
        } else {
            return this.memoryStorage[key] || null;
        }
    }

    removeItem(key) {
        if (this.storageAvailable) {
            localStorage.removeItem(key);
        } else {
            delete this.memoryStorage[key];
        }
    }

    // 调试和诊断
    diagnoseStorage() {
        const diagnosis = {
            storageAvailable: this.storageAvailable,
            hasSaveData: this.hasSaveData(),
            storageUsage: this.getStorageUsage(),
            backupCount: this.loadBackups().length,
            lastSaveTime: null,
            settings: this.loadSettings(),
            achievements: this.loadAchievements().size,
            quickSaves: this.getQuickSaveSlots()
        };

        const saveData = this.loadGameData();
        if (saveData) {
            diagnosis.lastSaveTime = new Date(saveData.timestamp).toLocaleString();
        }

        return diagnosis;
    }
    
    // 快速存档系统
    setupQuickSaveSystem() {
        // 绑定快速存档按钮事件
        for (let i = 1; i <= this.maxQuickSaves; i++) {
            const slotBtn = document.getElementById(`quickSave${i}`);
            if (slotBtn) {
                slotBtn.addEventListener('click', (e) => {
                    if (e.ctrlKey) {
                        // Ctrl+点击加载
                        this.loadQuickSave(i);
                    } else {
                        // 普通点击保存
                        this.saveQuickSave(i);
                    }
                });
                
                // 更新存档槽显示
                this.updateQuickSaveSlot(i);
            }
        }
    }
    
    saveQuickSave(slot) {
        if (!window.gameEngine) return false;
        
        try {
            const gameState = window.gameEngine.getGameState();
            const characterData = window.characterSystem ? window.characterSystem.saveCharacterData() : null;
            const progressData = window.progressTracker ? window.progressTracker.stats : null;
            
            const quickSaveData = {
                version: '1.0.0',
                slot: slot,
                gameState: gameState,
                characterData: characterData,
                progressData: progressData,
                timestamp: Date.now(),
                preview: this.generateSavePreview(gameState)
            };
            
            this.setItem(`${this.quickSaveKey}_${slot}`, JSON.stringify(quickSaveData));
            this.updateQuickSaveSlot(slot);
            
            // 显示保存成功提示
            this.showSaveNotification(`快速存档 ${slot} 已保存`, 'success');
            
            return true;
        } catch (error) {
            console.error(`快速存档 ${slot} 保存失败:`, error);
            this.showSaveNotification(`快速存档 ${slot} 保存失败`, 'error');
            return false;
        }
    }
    
    loadQuickSave(slot) {
        try {
            const quickSaveData = this.getItem(`${this.quickSaveKey}_${slot}`);
            if (!quickSaveData) {
                this.showSaveNotification(`存档槽 ${slot} 为空`, 'warning');
                return false;
            }
            
            const saveData = JSON.parse(quickSaveData);
            
            if (window.gameEngine) {
                window.gameEngine.loadGameState(saveData.gameState);
            }
            
            if (window.characterSystem && saveData.characterData) {
                window.characterSystem.loadCharacterData(saveData.characterData);
            }
            
            if (window.progressTracker && saveData.progressData) {
                window.progressTracker.stats = saveData.progressData;
            }
            
            this.showSaveNotification(`已加载存档槽 ${slot}`, 'success');
            return true;
        } catch (error) {
            console.error(`快速存档 ${slot} 加载失败:`, error);
            this.showSaveNotification(`存档槽 ${slot} 加载失败`, 'error');
            return false;
        }
    }
    
    updateQuickSaveSlot(slot) {
        const slotBtn = document.getElementById(`quickSave${slot}`);
        if (!slotBtn) return;
        
        const quickSaveData = this.getItem(`${this.quickSaveKey}_${slot}`);
        
        if (quickSaveData) {
            slotBtn.classList.add('has-save');
            try {
                const saveData = JSON.parse(quickSaveData);
                const date = new Date(saveData.timestamp);
                slotBtn.title = `存档时间: ${date.toLocaleString()}\n${saveData.preview || ''}`;
            } catch (error) {
                slotBtn.title = '存档数据异常';
            }
        } else {
            slotBtn.classList.remove('has-save');
            slotBtn.title = `存档槽 ${slot} - 点击保存，Ctrl+点击加载`;
        }
    }
    
    getQuickSaveSlots() {
        const slots = {};
        for (let i = 1; i <= this.maxQuickSaves; i++) {
            const quickSaveData = this.getItem(`${this.quickSaveKey}_${i}`);
            if (quickSaveData) {
                try {
                    const saveData = JSON.parse(quickSaveData);
                    slots[i] = {
                        timestamp: saveData.timestamp,
                        preview: saveData.preview,
                        hasData: true
                    };
                } catch (error) {
                    slots[i] = { hasData: false, error: true };
                }
            } else {
                slots[i] = { hasData: false };
            }
        }
        return slots;
    }
    
    generateSavePreview(gameState) {
        if (!gameState) return '未知状态';
        
        const chapter = gameState.currentChapter || 1;
        const scene = gameState.currentScene || '开始';
        
        return `第${chapter}章 - ${scene}`;
    }
    
    showSaveNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `save-notification ${type}`;
        notification.textContent = message;
        
        // 设置样式
        Object.assign(notification.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '12px 20px',
            borderRadius: '8px',
            color: 'white',
            fontWeight: '500',
            zIndex: '10000',
            transform: 'translateX(100%)',
            transition: 'transform 0.3s ease',
            backgroundColor: type === 'success' ? '#4ade80' : 
                           type === 'error' ? '#f87171' : 
                           type === 'warning' ? '#fbbf24' : '#60a5fa'
        });
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);
        
        // 自动移除
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }
    
    // 存档导入导出功能
    exportSaveData() {
        try {
            const exportData = {
                version: '1.0.0',
                timestamp: Date.now(),
                gameData: this.loadGameData(),
                settings: this.loadSettings(),
                achievements: Array.from(this.loadAchievements()),
                quickSaves: this.getQuickSaveSlots(),
                characterData: window.characterSystem ? window.characterSystem.saveCharacterData() : null,
                progressData: window.progressTracker ? window.progressTracker.stats : null
            };
            
            const dataStr = JSON.stringify(exportData, null, 2);
            const blob = new Blob([dataStr], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = `timeecho_save_${new Date().toISOString().slice(0, 10)}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            this.showSaveNotification('存档导出成功', 'success');
            return true;
        } catch (error) {
            console.error('导出存档失败:', error);
            this.showSaveNotification('存档导出失败', 'error');
            return false;
        }
    }
    
    importSaveData(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const importData = JSON.parse(e.target.result);
                    
                    if (importData.gameData) {
                        this.setItem(this.saveKey, JSON.stringify(importData.gameData));
                    }
                    
                    if (importData.settings) {
                        this.setItem(this.settingsKey, JSON.stringify(importData.settings));
                    }
                    
                    if (importData.achievements) {
                        this.saveAchievements(new Set(importData.achievements));
                    }
                    
                    this.showSaveNotification('存档导入成功', 'success');
                    resolve(true);
                } catch (error) {
                    console.error('导入存档失败:', error);
                    this.showSaveNotification('存档文件格式错误', 'error');
                    reject(error);
                }
            };
            
            reader.onerror = () => {
                this.showSaveNotification('文件读取失败', 'error');
                reject(new Error('文件读取失败'));
            };
            
            reader.readAsText(file);
        });
    }
}

// 创建全局存档系统实例
window.saveSystem = new SaveSystem();